package com.leexuan.ordersystem.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.leexuan.ordersystem.db.ProductDB;
import com.leexuan.ordersystem.db.SortDB;

public class ListProductBySortAction extends Action {

	public ListProductBySortAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		ArrayList products = null;

		ProductDB db = new ProductDB();
		SortDB sdb = new SortDB();

		int sortid = 0;

		if (request.getParameter("sid") != null) {
			sortid = Integer.parseInt(request.getParameter("sid"));
		}

		try {
			db.getConnection();

			if (sortid == 0) {
				products = db.getProducts();
			} else {
				products = db.getProductsBySid(sortid);

			}

			sdb.getConnection();

			HttpSession session = request.getSession();
			session.setAttribute("products", products);
			session.setAttribute("sorts", sdb.getSorts());

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				db.closeConnection();
				sdb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
